<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>DataSource &amp; DriverManager</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="jee tutorial, Java, web application, DataSource &amp; DriverManager">
<meta name="description" content="This part of the Java EE 5 tutorials covers DataSource &amp; DriverManager.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href=".." title="Contents">Contents</a>


<h1>DataSource &amp; DriverManager</h1>

<p>
In this part of the JEE 5 tutorials, we will compare <b>DataSource</b> 
object with the <b>DriverManager</b> object. 
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 

<p>
DataSource and the DriverManager are the two basic ways to connect to a 
database in a JEE application. The DriverManager is older facility, 
DataSource is newer. It is recommended to use the new DataSource facility 
to connect to databases and other resources. DataSource facility has several 
advantages over DriverManager facility. Using DataSource increases portability.
The DataSource enables connection pooling and distributed transactions, 
the DriverManager does not allow such techniques. Properties of a DataSource 
are kept in a configuration file. Any changes to the data source or database drivers
are made in the configuration file. In case of a DriverManager, these properties 
are hard coded in the application and for any changes we must recompile the code.
</p>

<p>
In this chapter, we will have two examples. One of the examples will use a DriverManager, 
the other one will use a DataSource to connect to a MySQL database. 
</p>


<pre class="code">
mysql> describe books;
+--------+--------------+------+-----+---------+----------------+
| Field  | Type         | Null | Key | Default | Extra          |
+--------+--------------+------+-----+---------+----------------+
| id     | int(11)      | NO   | PRI | NULL    | auto_increment | 
| author | varchar(30)  | YES  |     | NULL    |                | 
| title  | varchar(40)  | YES  |     | NULL    |                | 
| year   | int(11)      | YES  |     | NULL    |                | 
| remark | varchar(100) | YES  |     | NULL    |                | 
+--------+--------------+------+-----+---------+----------------+
5 rows in set (0.27 sec)
</pre>

<p>
We will use a books table. 
</p>


<h2>DriverManager</h2>

<p>
The first example will use a DriverManager. 
</p>

<div class="codehead">style.css</div>
<pre class="code">
* { font-size: 12px; font-family: Verdana }

td { border: 1px solid #ccc; padding: 3px }
th { border: 1px solid #ccc; padding: 3px; 
    background: #009999; color: white }

</pre>

<p>
This is the stylesheet file. 
</p>

<div class="codehead">web.xml</div>
<pre class="code">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;web-app&gt;
    &lt;servlet&gt;
        &lt;servlet-name&gt;DriverManager&lt;/servlet-name&gt;
        &lt;servlet-class&gt;com.zetcode.DriverManagerExample&lt;/servlet-class&gt;
    &lt;/servlet&gt;
    &lt;servlet-mapping&gt;
        &lt;servlet-name&gt;DriverManager&lt;/servlet-name&gt;
        &lt;url-pattern&gt;/DriverManager&lt;/url-pattern&gt;
    &lt;/servlet-mapping&gt;
    &lt;session-config&gt;
        &lt;session-timeout&gt;
            30
        &lt;/session-timeout&gt;
    &lt;/session-config&gt;
&lt;/web-app&gt;
</pre>

<p>
In the <i>web.xml</i> configuration file, we configure our servlet. 
</p>

<div class="codehead">DriverManagerExample.java</div>
<pre class="code">
package com.zetcode;

import java.io.*;
import java.net.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;


public class DriverManagerExample extends HttpServlet {

  static final String url = "jdbc:mysql://localhost:3306/books";


  protected void processRequest(HttpServletRequest request, 
          HttpServletResponse response)
          throws ServletException, IOException {

      response.setContentType("text/html;charset=UTF-8");
      PrintWriter out = response.getWriter();

      try {


        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(url, "root", "");

        Statement stmt = con.createStatement();
        ResultSet result = stmt.executeQuery("SELECT * FROM books");

        out.print("&lt;html&gt;");
        out.print("&lt;head&gt;");
        out.print("&lt;title&gt;Servlet NewServlet&lt;/title&gt;");
        out.print("&lt;link rel='stylesheet' href='style.css' type='text/css'&gt;");
        out.print("&lt;/head&gt;");
        out.print("&lt;body&gt;");

        out.print("&lt;table&gt;");
        out.print("&lt;tr&gt;");
        out.print("&lt;th&gt;Author&lt;/th&gt;");
        out.print("&lt;th&gt;Title&lt;/th&gt;");
        out.print("&lt;th&gt;Year&lt;/th&gt;");
        out.print("&lt;th&gt;Remark&lt;/th&gt;");
        out.print("&lt;/tr&gt;");


        while (result.next()) {
            out.print("&lt;tr&gt;");
            out.print("&lt;td&gt;");
            out.print(result.getString("author"));
            out.print("&lt;/td&gt;");
            out.print("&lt;td&gt;");
            out.print(result.getString("title"));
            out.print("&lt;/td&gt;");
            out.print("&lt;td&gt;");
            out.print(result.getString("year"));
            out.print("&lt;/td&gt;");
            out.print("&lt;td&gt;");
            out.print(result.getString("remark"));
            out.print("&lt;/td&gt;");
            out.print("&lt;/tr&gt;");
        }

        con.close();

        } catch (SQLException ex) {
            Logger.getLogger(DriverManagerExample.class.getName()).log(
                    Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DriverManagerExample.class.getName()).log(
                    Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }


    protected void doGet(HttpServletRequest request, 
        HttpServletResponse response)
        throws ServletException, IOException {

          processRequest(request, response);
    }


    protected void doPost(HttpServletRequest request,
        HttpServletResponse response)  
        throws ServletException, IOException {

          processRequest(request, response);
    }

}
</pre>

<p>
The example will display a books table from the books database in a html table. 
</p>

<pre class="explanation">
static final String url = "jdbc:mysql://localhost:3306/books";
</pre>

<p>
We provide the connection url. This is an url for a MySQL database. 
</p>

<pre class="explanation">
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "");
</pre>

<p>
We load the driver and get the connection to the database. 
</p>

<img src="/img/java/jee/drivermanager.png" alt="DriverManager">
<div class="figure">Figure: DriverManager</div>



<h2>DataSource</h2>

<p>
The next example uses the DataSource facility. We use the same data.
</p>

<div class="codehead">style.css</div>
<pre class="code">
* { font-size: 12px; font-family: Verdana }

td { border: 1px solid #ccc; padding: 3px }
th { border: 1px solid #ccc; padding: 3px; 
    background: #009999; color: white }
</pre>

<p>
Simple stylesheet. 
</p>


<div class="codehead">resin-web.xml</div>
<pre class="code">
&lt;web-app xmlns="http://caucho.com/ns/resin"&gt;
  &lt;!--
     - Configures the database.
     -
     - jndi-name specifies the JNDI name
     - type      specifies the driver class
     - path      is a driver-specific configuration parameter
    --&gt;
 &lt;database&gt;
 &lt;jndi-name&gt;jdbc/mysql&lt;/jndi-name&gt;
  &lt;driver&gt;
    &lt;type&gt;com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource&lt;/type&gt;
    &lt;url&gt;jdbc:mysql://localhost:3306/books&lt;/url&gt;
    &lt;user&gt;root&lt;/user&gt;
    &lt;password&gt;&lt;/password&gt;
  &lt;/driver&gt;
  &lt;/database&gt;

  &lt;!--
     - Configures the initialization servlet.  The bean-style init
     - it used to look up the JNDI DataSource in the configuration file.
    --&gt;

   &lt;servlet&gt;
    &lt;servlet-name&gt;datasource&lt;/servlet-name&gt;
    &lt;servlet-class&gt;com.zetcode.DataSourceExample&lt;/servlet-class&gt;
        &lt;init&gt;
      &lt;data-source&gt;${jndi:lookup('jdbc/mysql')}&lt;/data-source&gt;
    &lt;/init&gt;
  &lt;/servlet&gt;

  &lt;servlet-mapping&gt;
    &lt;url-pattern&gt;/DataSource&lt;/url-pattern&gt;
    &lt;servlet-name&gt;datasource&lt;/servlet-name&gt;
  &lt;/servlet-mapping&gt;

&lt;/web-app&gt;
</pre>

<p>
This is the <i>resin-web.xml</i> configuration style. It is Resin 
specific. It overrides the configuration in the <i>web.xml</i> file. 
In our file, we configure the datasource and the servlet mapping. 
</p>


<p>
The DataSource configuration is done within the &lt;database&gt; tags. We specify 
the driver type, connection url, user name
and password. 
</p>

<p>
In our example, we use the JNDI (The Java Naming and Directory Interface) API. 
This API is used to look up data and objects via a name. The JNDI enables 
separation of resource configuration from the application code. 
</p>


<div class="codehead">DataSourceExample.java</div>
<pre class="code">
package com.zetcode;

import java.io.*;
import java.net.*;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.DataSource;

public class DataSourceExample extends HttpServlet {

    private DataSource _ds = null;


    public void setDataSource(DataSource ds) {
        _ds = ds;
    }


    public void init()
            throws ServletException {
        if (_ds == null) {

            throw new ServletException("datasource not properly configured");
        }
    }

    protected void processRequest(HttpServletRequest request, 
            HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();


        try {

          Connection conn = _ds.getConnection();

          Statement stmt = conn.createStatement();
          ResultSet result = stmt.executeQuery("SELECT * FROM books");

          out.print("&lt;html&gt;");
          out.print("&lt;head&gt;");
          out.print("&lt;title&gt;DataSource&lt;/title&gt;");
          out.print("&lt;link rel='stylesheet' href='style.css' type='text/css'&gt;");
          out.print("&lt;/head&gt;");
          out.print("&lt;body&gt;");

          out.print("&lt;table&gt;");
          out.print("&lt;tr&gt;");
          out.print("&lt;th&gt;Author&lt;/th&gt;");
          out.print("&lt;th&gt;Title&lt;/th&gt;");
          out.print("&lt;th&gt;Year&lt;/th&gt;");
          out.print("&lt;th&gt;Remark&lt;/th&gt;");
          out.print("&lt;/tr&gt;");


          while (result.next()) {
              out.print("&lt;tr&gt;");
              out.print("&lt;td&gt;");
              out.print(result.getString("author"));
              out.print("&lt;/td&gt;");
              out.print("&lt;td&gt;");
              out.print(result.getString("title"));
              out.print("&lt;/td&gt;");
              out.print("&lt;td&gt;");
              out.print(result.getString("year"));
              out.print("&lt;/td&gt;");
              out.print("&lt;td&gt;");
              out.print(result.getString("remark"));
              out.print("&lt;/td&gt;");
              out.print("&lt;/tr&gt;");
           }


          out.print("&lt;/table&gt;");
          out.println("&lt;/body&gt;");
          out.println("&lt;/html&gt;");

          result.close();
          stmt.close();
          conn.close();

        } catch (SQLException ex) {
            Logger.getLogger(DataSourceExample.class.getName()).log(
                    Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

    protected void doGet(HttpServletRequest request, 
            HttpServletResponse response)
            throws ServletException, IOException {

        processRequest(request, response);
    }

    protected void doPost(HttpServletRequest request, 
            HttpServletResponse response)
            throws ServletException, IOException {

        processRequest(request, response);
    }
}
</pre>


<p>
The example will display a books table from the books
database in a html table too.
</p>



<pre class="explanation">
public void setDataSource(DataSource ds) {
    _ds = ds;
}
</pre>

<p>
The method is called by the Resin application server at configuration time. 
</p>



<pre class="explanation">
public void init()
        throws ServletException {
    if (_ds == null) {

        throw new ServletException("datasource not properly configured");
    }
}
</pre>

<p>
The <code>init()</code> method checks whether the datasource was configured properly.
</p>


<pre class="explanation">
Connection conn = _ds.getConnection();
</pre>

<p>
We get the connection from the datasource object. 
</p>

<p>
This chapter of the JEE tutorials was about DataSource and DriverManager.
</p>

<img src="/img/java/jee/datasource.png" alt="DataSource">
<div class="figure">Figure: DataSource</div>

<p>
In this chapter we have briefly mentioned DataSource and DriverManager.
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br> 


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified April 8, 2008  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body> 
</html>

